package com.yunfei.api.v2;
import com.google.gson.Gson;
import com.yunfei.api.v2.contants.FaceContants;
import com.yunfei.api.v2.contants.ImagesContant;
import com.yunfei.api.v2.contants.QueryHeTongSignInfoContant;
import com.yunfei.api.v2.param.aliyun.BankCard4cParam;
import com.yunfei.api.v2.param.aliyun.FaceCheckFormParam;
import com.yunfei.api.v2.param.aliyun.FaceCheckParam;
import com.yunfei.api.v2.result.aliyun.card4.Card4ResultJSONRoot;
import com.yunfei.api.v2.result.aliyun.face.FaceLiveResultJSONRoot;
import com.yunfei.api.v2.result.aliyun.face.FaceResultJSONRoot;
import com.yunfei.api.v2.service.CaRenZhengService;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.contants.ApplicationConstant;
import com.yunfei.contants.PeopleFaceConstants;
import com.yunfei.enums.ResultStatus;
import com.yunfei.utils.DateUtil;
import com.yunfei.utils.aliyun.HttpUtils;
import com.yunfei.utils.file.PicYaSuo;
import com.yunfei.utils.id.IdUtils;
import com.yunfei.utils.string.StringUtil;
import com.yunfei.yunhetong.elecContCustIdenDtl.bo.ElecContCustIdenDtlBo;
import com.yunfei.yunhetong.elecContCustIdenDtl.service.ElecContCustIdenDtlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static com.yunfei.utils.file.PicYaSuo.byte2image;
import static com.yunfei.utils.file.PicYaSuo.compressUnderSize;

/**
 * @Description: 人脸识别和验证银行卡四要素接口
 * @Author: zhengyunfei
 * @Date: 2018/6/15
 * @time:11:26
 */
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/api/v2/aliyun")
@Api(value = QueryHeTongSignInfoContant.FACE_NAMESPACE+ ImagesContant.IMG_STR,tags =  QueryHeTongSignInfoContant.FACE_NAMESPACE+ ImagesContant.IMG_STR )
public class FaceApiController {
    @Autowired
    private Environment env;
    @Autowired
    private ElecContCustIdenDtlService elecContCustIdenDtlService;
    @Autowired
    private CaRenZhengService caRenZhengService;

    /**
     * @Description: 人脸识别
     * @Author: zhengyunfei
     * @Date: 2019/7/29
     * @time:10:30
     */
    @PostMapping(value="/facecheck")
    @ApiOperation(position = 3,value = FaceContants.facecheck_api+ ImagesContant.IMG_STR,notes = FaceContants.facecheck_api_note,response = ResultModel.class)
    @ResponseBody
    public Object facecheck(FaceCheckParam param, FaceCheckFormParam faceCheckFormParam,HttpServletRequest request, HttpServletResponse response){
        ResultModel resultModel=new ResultModel();
        String custNo=faceCheckFormParam.getCustId();
        String loginMobile=faceCheckFormParam.getLoginMobile();
        try {
            String host = "https://facecheck.market.alicloudapi.com";
            String path = "/facecheck";
            String method = "POST";
            String appcode = PeopleFaceConstants.AppCode;
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fxxxxxxxxxxxx
            headers.put("Authorization", "APPCODE " + appcode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            String idCardNum=param.getIdCardNum();
            String image=param.getImage();
            if(StringUtil.isNullOrEmpty(image)){
                image=yasuoFace(request, response);
            }
            //活体检测
            int checkCode=checkLive(image);
            if(checkCode!=0){
                resultModel.setMessage("活体检测不通过");
                resultModel.setCode(3);
                resultModel.setData("0301000");
                return resultModel;
            }
            String realName=param.getRealName();
            bodys.put("idCardNum", idCardNum);
            bodys.put("image", image);
            bodys.put("realName", realName);
            HttpResponse httpResponse = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //System.out.println(response.toString());
            //System.out.println(EntityUtils.toString(response.getEntity()));
            String result=EntityUtils.toString(httpResponse.getEntity());
            Gson gson=new Gson();
            FaceResultJSONRoot resultJson=gson.fromJson(result, FaceResultJSONRoot.class);
            if(!StringUtil.isNullOrEmpty(resultJson)){
                int code=resultJson.getCode();
                String idenResu="";
                if(code==0){
                    idenResu=FaceContants.Y;
                }else{
                    idenResu=FaceContants.N;
                }
                //保存人脸识别
                ElecContCustIdenDtlBo elecContCustIdenDtlBo=new ElecContCustIdenDtlBo();
                if(!StringUtil.isNullOrEmpty(faceCheckFormParam)){
                    elecContCustIdenDtlBo.setCustId(faceCheckFormParam.getCustId());//crm客户号
                    elecContCustIdenDtlBo.setCReserveno(faceCheckFormParam.getcReserveNo());//预约编号
                    elecContCustIdenDtlBo.setEntreMobileNo(loginMobile);//登录的手机号
                    elecContCustIdenDtlBo.setIdenTyp(FaceContants.IDEN_TYP_01);
                    elecContCustIdenDtlBo.setIdenDate(DateUtil.getAllTime());
                    elecContCustIdenDtlBo.setIdenResu(idenResu);
                    elecContCustIdenDtlBo.setIdenNo(idCardNum);//身份证号码
                    elecContCustIdenDtlBo.setCustNm(realName);//姓名
                    elecContCustIdenDtlService.add(elecContCustIdenDtlBo);
                    if(code==0){
                        //保存成功后，为客户进行caR恩正
                        caRenZhengService.caRenZheng(resultModel,custNo,loginMobile,"");
                    }

                }
            }

            return resultJson;

        }catch (Exception e){
            e.printStackTrace();
        }

        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }
    /**
    * @Description: 验证银行卡四要素
     * https://market.aliyun.com/products/57000002/cmapi033467.html?spm=5176.730005.productlist.d_cmapi033467.3d0c3524cY1tGG&innerSource=search_%E9%93%B6%E8%A1%8C%E5%8D%A1%E5%9B%9B%E8%A6%81%E7%B4%A0#sku=yuncode2746700003
    * @Author: zhengyunfei
    * @Date: 2019/11/8
    * @time:9:10
    */
    @PostMapping(value="/bankcard4c")
    @ApiOperation(position = 3,value = FaceContants.bankcard4c_api+ ImagesContant.IMG_STR,notes = FaceContants.bankcard4c_api_note,response = ResultModel.class)
    @ResponseBody
    public Object bankcard4c(BankCard4cParam param,FaceCheckFormParam faceCheckFormParam){
        ResultModel resultModel=new ResultModel();
        String loginMobile=faceCheckFormParam.getLoginMobile();
        String host = "https://bankcard4c.shumaidata.com";
        String path = "/bankcard4c";
        String method = "GET";
        String appcode = PeopleFaceConstants.AppCode;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        String bankcard=param.getBankcard();
        String idcard=param.getIdcard();
        String mobile=param.getMobile();
        String name=param.getName();
        querys.put("bankcard", bankcard);
        querys.put("idcard", idcard);
        querys.put("mobile", mobile);
        querys.put("name", name);
        String custNo=faceCheckFormParam.getCustId();
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
           // System.out.println(response.toString());
            String result=EntityUtils.toString(response.getEntity());
            Gson gson=new Gson();
            Card4ResultJSONRoot resultJson=gson.fromJson(result, Card4ResultJSONRoot.class);
            if(!StringUtil.isNullOrEmpty(resultJson)){
                int code=resultJson.getData().getResult();
                String idenResu="";
                if(code==0){
                    idenResu=FaceContants.Y;
                }else{
                    idenResu=FaceContants.N;
                }
                //保存银行卡四要素
                ElecContCustIdenDtlBo elecContCustIdenDtlBo=new ElecContCustIdenDtlBo();
                if(!StringUtil.isNullOrEmpty(faceCheckFormParam)){
                    elecContCustIdenDtlBo.setCustId(faceCheckFormParam.getCustId());//crm客户号
                    elecContCustIdenDtlBo.setCReserveno(faceCheckFormParam.getcReserveNo());//预约编号
                    elecContCustIdenDtlBo.setEntreMobileNo(loginMobile);//登录的手机号
                    elecContCustIdenDtlBo.setIdenTyp(FaceContants.IDEN_TYP_01);
                    elecContCustIdenDtlBo.setIdenDate(DateUtil.getAllTime());
                    elecContCustIdenDtlBo.setIdenResu(idenResu);
                    elecContCustIdenDtlBo.setCradNo(bankcard);//银行卡号
                    elecContCustIdenDtlBo.setIdenNo(idcard);//身份证号码
                    elecContCustIdenDtlBo.setCustNm(name);//姓名
                    elecContCustIdenDtlBo.setMobileNo(mobile);//验证手机号
                    elecContCustIdenDtlService.add(elecContCustIdenDtlBo);
                    if(code==0){
                        //保存成功后，为客户进行caR恩正
                        caRenZhengService.caRenZheng(resultModel,custNo,loginMobile,mobile);
                    }

                }
            }
            return resultJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultModel;
    }

    /**
     * @Description: 人脸图片压缩
     * @Author: zhengyunfei
     * @Date: 2019/1/25
     * @time:10:32
     */
    @RequestMapping(value = "/face/yasuo",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ApiOperation(value = "人脸图片压缩",notes = "将上传的人脸图片压缩到100k以内,并返回base64编码<span color='red'>可以不用此接口，此接口与集成到人脸识别验证接口里面，人脸验证接口可以自动压缩</span>",position = 1)
    @ResponseBody
    public Object faceYaSuo(HttpServletRequest request, HttpServletResponse response){
        ResultModel resultModel=new ResultModel();
        String base64Str=yasuoFace(request, response);
        resultModel.setData(base64Str);
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }
  /**
  * @Description: 图片压缩
  * @Param: [request, response, resultModel]
  * @return: boolean
  * @Author: zhengyunfei
  * @Date: 2019/11/11
  * @time:15:02
  */
    private String yasuoFace(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String base64Str="";
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) + "files/";
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile1 = multipartHttpServletRequest.getFile("file");
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            if (!imgFile1.isEmpty()) {
                //获取前端传来的文件名
                String fileName = imgFile1.getOriginalFilename();
                // 设置存放图片文件的路径
                String today= DateUtil.getToDay("yyyyMMdd");
                try {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                    String picId= IdUtils.getId();//随机生成图片，防止图片重复
                    String filePath=uploadPath+"face/"+today+"/"+picId+"."+fileExt;
                    try {
                        //利用文件流保存文件
                        File saveFile= new File(filePath);
                        File parentFile=saveFile.getParentFile();
                        if(!parentFile.exists()&&!parentFile.isDirectory()){
                            parentFile.mkdirs();
                        }
                        if(!saveFile.exists())
                        {
                            try {
                                saveFile.createNewFile();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        imgFile1.transferTo(saveFile);
                        byte[] imgBytes = PicYaSuo.getByteByPic(filePath);
                        //对图片进行压缩到100k以内
                        byte[] resultImg = compressUnderSize(imgBytes,100 * 1024);
                        System.out.println("开始对图片进行压缩处理："+resultImg.length);

                        String shortFacePath=uploadPath+"shortFace/"+today+"/"+picId+"."+fileExt;
                        //设置压缩后的图片保存路径
                        File shortParentPath= new File(uploadPath+"shortFace/"+today);
                        if(!shortParentPath.exists()&&!shortParentPath.isDirectory()){
                            shortParentPath.mkdirs();
                        }
                        //String shortFacePath=uploadPath+"shortFace/"+picId+"."+fileExt;
                        System.out.println("压缩后的路径："+shortFacePath);
                        byte2image(resultImg,shortFacePath);
                        //将图片转换为base64编码
                        System.out.println("用户头像上传路径："+filePath);
                        String fileUrl = imageDomain  + "face/" +today+"/"+picId+"."+fileExt;
                       //将压缩后的图片转换为base64编码
                        base64Str=GetImageStr(shortFacePath);
                        return base64Str;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return base64Str;
    }

    /**
     * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
     * @param imgFilePath 图片路径
     * @return String
     */
    public static String GetImageStr(String imgFilePath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        return Base64.getEncoder().encodeToString(data);
    }
public static int checkLive(String base64){
    String host = "http://livebody.market.alicloudapi.com";
    String path = "/checklive";
    String method = "POST";
    String appcode = PeopleFaceConstants.AppCode;
    Map<String, String> headers = new HashMap<String, String>();
    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    //根据API的要求，定义相对应的Content-Type
    headers.put("Content-Type", "application/json; charset=UTF-8");
    Map<String, String> querys = new HashMap<String, String>();
    String bodys = "{\"ImgBase64\":\""+base64+"\"}";
    try {
        /**
         * 重要提示如下:
         * HttpUtils请从
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
         * 下载
         *
         * 相应的依赖请参照
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
         */
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

        //获取response的body
       String result=EntityUtils.toString(response.getEntity());
        System.out.println("活体检测返回结果==============="+result);
        Gson gson=new Gson();
        FaceLiveResultJSONRoot resultJson=gson.fromJson(result, FaceLiveResultJSONRoot.class);
        return resultJson.getCode();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}
    public static void main(String args[]){
        String host = "https://facecheck.market.alicloudapi.com";
        String path = "/facecheck";
        String method = "POST";
        String appcode = PeopleFaceConstants.AppCode;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fxxxxxxxxxxxx
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idCardNum", "411422198809021214");
        String image="";
        bodys.put("image", image);
        bodys.put("realName", "郑云");


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
